import axios from 'axios';
import { Message } from 'element-ui';
import router from "../router";
 
const Axios = axios.create({
  baseURL: "/", // 因为我本地做了反向代理
  timeout: 60000,
  responseType: "json",
  withCredentials: true, // 是否允许带cookie这些
  headers: {
    "Content-Type": "application/json;charset=utf-8"
  }
});
 
Axios.defaults.isRetryRequest = false;

//POST传参序列化(添加请求拦截器)
Axios.interceptors.request.use(
  config => {
    if (localStorage.token) {
      config.headers.Authorization = localStorage.token;
    }
    return config;
  },
  error => {
    Message({
      message: error && error.data.error.message,
      type: 'error'
    });
    return Promise.reject(error.data.error.message);
  }
);
 
 
//http response 拦截器
 
//刷新token的请求方法
function getRefreshToken() {
  return axios.get('/api/auth/login/refreshToken?token='+localStorage.token);
}

//返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(
  res => {
    return res;
  },
  error => {
    // 用户登录的时候会拿到一个基础信息,比如用户名,token,过期时间戳
    // 直接丢localStorage或者sessionStorage
    let errorInfo = '';
    if (!localStorage.token) {
      // 若是接口访问的时候没有发现有鉴权的基础信息,直接返回登录页
      router.push({
        path: "/login"
      });
    } else {
        // 401未授权,需要到后台判断refreshToken是否过期,如果过期,则重新登录,如果未过期,只需要重新刷新
        
        switch (error.response.status) {
          case 401:
            let config = error.config;
            if (!config.isRetryRequest) {
              return getRefreshToken()
                  .then(function (res) {
                      let data = res.data;
                      //修改flag
                      config.isRetryRequest = true;
                      //修改原请求的token
                      config.headers.Authorization = data.data;
                      /*这边不需要baseURL是因为会重新请求url
                      *url中已经包含baseURL的部分了
                      *如果不修改成空字符串，会变成'api/api/xxxx'的情况*/
                      config.baseURL = '';
                      localStorage.setItem("token",data.data);
                      //重新请求
                      return axios(config);
                  })
                  .catch(function () {
                  //刷新token失败只能跳转到登录页重新登录
                      Message.error('登录状态信息过期,请重新登录!');
                      router.push({
                        path:"/login",
                        querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
                      })
                      throw error;
                  });
          }
          break;
          case 400:
            errorInfo =  error.response.data.message;
            Message.error("后台运行错误!"+errorInfo);
          break;
          case 403:
            router.push({
              path:"/403",
              querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
            })
          break;
        }
    }
    
    return Promise.reject(errorInfo);
  }
);
 
 
 
/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
 
export function fetch(url,params={}){
  return new Promise((resolve,reject) => {
    Axios.get(url,{
      params:params
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}
 
/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
 
export function post(url,data = {}){
  
  return new Promise((resolve,reject) => {
    Axios.post(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}
 
/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */
 
export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    Axios.patch(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}
 
/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */
 
export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    Axios.put(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}
/**
 * 封装delete请求
 * @param url
 * @param data
 * @returns {Promise}
 */
 
export function del(url,params={}){
  return new Promise((resolve,reject) => {
    Axios.delete(url,{
      params:params
    }).then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * 封装下载文件请求
 * @param url
 * @param params
 * @returns {Promise}
 */
 
export function download(url,params={}){
  return new Promise((resolve,reject) => {
    Axios({
        methods: 'get',
        url: url,
        params:params,
        responseType: 'blob'
    }).then(response => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    })
  })
}
/**
 * 封装小图片请求
 * @param url
 * @param params
 * @returns {Promise}
 */
 
export function fetchImg(url,params={}){
  return new Promise((resolve,reject) => {
    Axios({
        methods: 'get',
        url: url,
        params:params,
        responseType: 'arraybuffer'
    }).then(response => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    })
  })
}
